package manager;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.primefaces.model.SortOrder;

import constants.Globals;

import util.DateHelper;
import util.HibernateUtil;

import domain.LogServiceCallDAO;
import domain.OrgBirimDAO;
import domain.OrgKullaniciDAO;
import domain.OrgOrganizasyonDAO;
import exception.IBToolsException;

@SuppressWarnings("unchecked")
public class ScreenDAOManager {

	public static List<OrgKullaniciDAO> findKullanici(
			OrgKullaniciDAO searchKullanici, int start, int pageSize, String sortField, SortOrder sortOrder) throws IBToolsException{
    	Session session = HibernateUtil.getDEVSession();
    	Transaction tx = null;
    	List<OrgKullaniciDAO> list = null;
    	try {
			tx = HibernateUtil.beginDEVTransaction(session);
	    	list = (List<OrgKullaniciDAO>)
	    			CommonDAOManager.criteriaByExample(session, OrgKullaniciDAO.class, searchKullanici, start, pageSize, sortField, sortOrder, false, true).list();
			tx.commit();
			
		} catch (HibernateException e) {
			tx.rollback();
			throw e;
		}
    	return list;
	}
	
	public static int findKullaniciCount(
		OrgKullaniciDAO searchKullanici, int pageNo, int pageSize, String sortField, SortOrder sortOrder) throws IBToolsException{
    	Session session = HibernateUtil.getDEVSession();
    	Transaction tx = null;
    	Long rowCount = null;
    	try {
			tx = HibernateUtil.beginDEVTransaction(session);
	    	rowCount = (Long)
	    			CommonDAOManager.criteriaByExample(session, OrgKullaniciDAO.class, searchKullanici, pageNo, pageSize, sortField, sortOrder, true, true).uniqueResult();
			tx.commit();
			
		} catch (HibernateException e) {
			tx.rollback();
			throw e;
		}
    	return rowCount.intValue();
	}

	public static List<LogServiceCallDAO> loadHistory(int start, int pageSize, String sortField, SortOrder sortOrder, String historyServiceNameFilter,
			String historyCallDateFilter, String userCode, int isSuccessful) throws IBToolsException, ParseException{
    	Session session = HibernateUtil.getDEVSession();
    	Transaction tx = null;
    	List<LogServiceCallDAO> list = null;
    	LogServiceCallDAO callDAO = new LogServiceCallDAO();
    	callDAO.setUserCode(SessionManager.getLoginUserCode());
    	try {
			tx = HibernateUtil.beginDEVTransaction(session);
	    	Criteria criteria = session.createCriteria(LogServiceCallDAO.class);
	    	if(isSuccessful > -1){
	    		criteria.add(Restrictions.eq("success", isSuccessful == 1));
	    	}
	    	if(!userCode.equalsIgnoreCase(Globals.EMPTY_STRING)){
	    		criteria.add(Restrictions.eq("userCode", userCode));
	    	}
    		if(!historyServiceNameFilter.equalsIgnoreCase(Globals.EMPTY_STRING)){
	    		String preLike = historyServiceNameFilter.startsWith(".") ? "" : "%";
	    		String postLike = historyServiceNameFilter.endsWith(".") ? "" : "%";
	    		historyServiceNameFilter = historyServiceNameFilter.replaceAll("\\.", "");
	    		criteria.add(Restrictions.like("serviceName", preLike + historyServiceNameFilter.toUpperCase() + postLike));
    		}
    		if(!historyCallDateFilter.equalsIgnoreCase(Globals.EMPTY_STRING)){
    			SimpleDateFormat d = new SimpleDateFormat("yyyyMMdd");
    			Date toSearch = d.parse(historyCallDateFilter);
    			Date fromDate = DateHelper.getDateWithoutTime(toSearch);
    			Date toDate = DateHelper.getDateWithoutTime(DateHelper.getTomorrowDate(toSearch));
        		criteria.add(Restrictions.ge("callDatetimestamp", fromDate ));
        		criteria.add(Restrictions.le("callDatetimestamp", toDate ));
    		}
    		criteria = CommonDAOManager.paginateCriteria(criteria, start, pageSize, sortField, sortOrder, false, false);
	    	list = (List<LogServiceCallDAO>) criteria.list();
			tx.commit();
			
		} catch (HibernateException e) {
			tx.rollback();
			throw e;
		}
    	return list;
	}
	
	public static int loadHistoryCount(int pageNo, int pageSize, String sortField, SortOrder sortOrder, String historyServiceNameFilter, 
			String historyCallDateFilter, String userCode, int isSuccessful) throws IBToolsException, ParseException{
    	Session session = HibernateUtil.getDEVSession();
    	Transaction tx = null;
    	Long rowCount = null;
    	LogServiceCallDAO callDAO = new LogServiceCallDAO();
    	callDAO.setUserCode(SessionManager.getLoginUserCode());
    	try {
			tx = HibernateUtil.beginDEVTransaction(session);
			Criteria criteria = session.createCriteria(LogServiceCallDAO.class);
	    	if(isSuccessful > -1){
	    		criteria = criteria.add(Restrictions.eq("success", isSuccessful == 1));
	    	}
	    	if(!userCode.equalsIgnoreCase(Globals.EMPTY_STRING)){
	    		criteria = criteria.add(Restrictions.eq("userCode", userCode));
	    	}
    		if(!historyServiceNameFilter.equalsIgnoreCase(Globals.EMPTY_STRING)){
        		criteria = criteria.add(Restrictions.like("serviceName", historyServiceNameFilter.toUpperCase(), MatchMode.ANYWHERE));
    		}
    		if(!historyCallDateFilter.equalsIgnoreCase(Globals.EMPTY_STRING)){
    			SimpleDateFormat d = new SimpleDateFormat("yyyyMMdd");
    			Date toSearch = d.parse(historyCallDateFilter);
    			Date fromDate = DateHelper.getDateWithoutTime(toSearch);
    			Date toDate = DateHelper.getDateWithoutTime(DateHelper.getTomorrowDate(toSearch));
        		criteria = criteria.add(Restrictions.ge("callDatetimestamp", fromDate ));
        		criteria = criteria.add(Restrictions.le("callDatetimestamp", toDate ));
    		}
    		criteria.setProjection(Projections.rowCount());
    		
	    	rowCount = (Long) criteria.uniqueResult();
			tx.commit();
			
		} catch (HibernateException e) {
			tx.rollback();
			throw e;
		}
    	return rowCount.intValue();
	}
	
	public static List<OrgBirimDAO> completeBirim(String birimkoduQuery, int maxResult) throws IBToolsException{
    	Session session = HibernateUtil.getDEVSession();
    	Transaction tx = null;
    	List<OrgBirimDAO> list = null;
    	try {
			tx = HibernateUtil.beginDEVTransaction(session);
			list = (List<OrgBirimDAO>)
					CommonDAOManager.criteriaByCodeOrName(session, OrgBirimDAO.class, 
							"birimkodu", "birimadi", birimkoduQuery, maxResult)
							.add(Restrictions.eq("status", true)).list();
			tx.commit();
			
		} catch (HibernateException e) {
			tx.rollback();
			throw e;
		}
    	return list;
	}
	
	public static List<OrgOrganizasyonDAO> completeOrganizasyon(String organizasyonkoduQuery, int maxResult) throws IBToolsException{
    	Session session = HibernateUtil.getDEVSession();
    	Transaction tx = null;
    	List<OrgOrganizasyonDAO> list = null;
    	try {
			tx = HibernateUtil.beginDEVTransaction(session);
			list = (List<OrgOrganizasyonDAO>) 
					CommonDAOManager.criteriaByCodeOrName(session, OrgOrganizasyonDAO.class, 
							"organizasyonkodu", "organizasyonadi", organizasyonkoduQuery, maxResult)
							.add(Restrictions.eq("status", true)).list();
			tx.commit();
			
		} catch (HibernateException e) {
			tx.rollback();
			throw e;
		}
    	return list;
	}
	
}
